package Library.Events;

import java.awt.event.*;
import java.util.*;

/**
 * Event dient als een Multicast Delegation
 * Op dit event kunnen dus meerdere handlers worden geregistreerd.
 * @param <T>
 */
public class Event<T extends ActionEvent>
{
    /**
     *
     */
    protected final transient List<ActionListener> m_EventHandlers = Collections.synchronizedList(new ArrayList<ActionListener>());
    /**
     *
     * @param listener
     */
    public void register(ActionListener listener)
    {
	synchronized (m_EventHandlers)
	{
	    m_EventHandlers.add(listener);
	}
    }
    
    /**
     *
     * @param e
     */
    public void trigger(T e)
    {
	List<ActionListener> oldList = new ArrayList<ActionListener>();
	synchronized (m_EventHandlers)
	{
	    oldList.addAll(m_EventHandlers);
	}
	
	Iterator<ActionListener> it = oldList.iterator();
	while (it.hasNext())
	{
	    try
	    {
		it.next().actionPerformed(e);
	    }
	    catch (Exception ex)
	    {
		// Don't through else it could generate a deadlock
		ex.printStackTrace();
	    }
	}
    }
    
    /**
     *
     * @param listener
     */
    public void unregister(ActionListener listener)
    {
	synchronized (m_EventHandlers)
	{
            m_EventHandlers.remove(listener);
        }
    }
    
    /**
     *
     */
    public void clear()
    {
	synchronized (m_EventHandlers)
	{
	    m_EventHandlers.clear();
	}
    }
}
